package com.sdx.console.qaVideo.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.entity.CoreOrg;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.content.entity.ResColumn;
import com.sdx.console.content.entity.ResTag;
import com.sdx.console.content.service.ResColumnService;
import com.sdx.console.content.service.ResTagService;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.customer.service.CustomerInfoService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import com.sdx.console.qaVideo.entity.*;
import com.sdx.console.qaVideo.service.*;
import com.sdx.console.qaVideo.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * 视频 接口
 */
@RequestMapping("/qaVideo/qaVideo")
@Controller
public class QaVideoController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(QaVideoController.class);
    private static final String MODEL = "/qaVideo/qaVideo";

    @Resource
    private SQLManager sqlManager;

    @Resource
	private QaVideoService qaVideoService;

    @Resource
    private ResCloudFileService resCloudFileService;

    @Resource
    private CustomerInfoService customerInfoService;

    @Resource
    private ResTagService resTagService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setIsTeacher(1);
        List<CustomerInfo> customerInfoList =  customerInfoService.template(customerInfo);
        view.addObject("customerInfoList",customerInfoList);
        List<ResTag> list = resTagService.getValidList();
        view.addObject("resTagList", JSON.toJSONString(list));
        view.addObject("resTag", list);

	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("qaVideo.qaVideo.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("qaVideo.qaVideo.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer videoId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        QaVideo qaVideo = qaVideoService.queryById(videoId);
        view.addObject("qaVideo", qaVideo);
		setPageParam(view,request);
		try {
			view.addObject("qaVideoJson", JacksonUtils.toJsonString(qaVideo,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("qaVideo.qaVideo.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("qaVideo.qaVideo.query")
    @ResponseBody
    public JsonResult<PageQuery> list(QaVideo condtion)
    {
        PageQuery page = condtion.getPageQuery();
        qaVideoService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,QaVideo qaVideo,HttpServletRequest request,MultipartFile coverFile
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
        if (!FileUtils.isEmptyFile(coverFile)) {
            try
            {
                String coverFileNamePair = FileUtils.upload(subPath,coverFile);
                String coverStoreFile = coverFileNamePair.split("::")[0];
                coverStoreFile = subPath+coverStoreFile;
                AliOSSApi.uploadLocalFile(FileUtils.getRoot()+coverStoreFile,bucketName,coverStoreFile.substring(1));
                String coverUrl = "https://sdxcomm."+ ConfigService.ossDomain+coverStoreFile;
                qaVideo.setCover(coverUrl);
                resCloudFileService.insertResFile(ResCloudFile.ALI,coverStoreFile,coverUrl,"a","视频直播封面");
            }catch(Exception e) {
                e.printStackTrace();
                result.setCode(JsonReturnCode.IO_ERROR.getCode());
                result.setMsg(e.getMessage());
            }
        }
		CoreUser user = getLoginUser(request);
        if(qaVideo.getIsFee()==1){
            qaVideo.setFeeType(1);
        }

    	if (isNew) {
			qaVideo.setCreatedBy(user.getId().intValue());
			qaVideo.setCreatedName(user.getName());
			qaVideo.setCreatedTime(new Date());
			qaVideo.setUpdatedBy(user.getId().intValue());
			qaVideo.setUpdatedName(user.getName());
			qaVideo.setUpdatedTime(new Date());
			qaVideoService.save(qaVideo);
		} else {
			qaVideo.setUpdatedBy(user.getId().intValue());
			qaVideo.setUpdatedName(user.getName());
			qaVideo.setUpdatedTime(new Date());
			qaVideoService.updateTemplate(qaVideo);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("qaVideo.qaVideo.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)QaVideo qaVideo,HttpServletRequest request
            ,@RequestParam("coverFile") MultipartFile coverFile
		)
    {

        return save(true,qaVideo,request,coverFile
		);
    }

    @PostMapping("/update.json")
    @Function("qaVideo.qaVideo.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  QaVideo qaVideo,HttpServletRequest request
            ,@RequestParam("coverFile") MultipartFile coverFile
		) {
		return save(false,qaVideo,request,coverFile
		);
    }



    @GetMapping("/view.json")
    @Function("qaVideo.qaVideo.query")
    @ResponseBody
    public JsonResult<QaVideo>queryInfo(Integer videoId) {
        QaVideo qaVideo = qaVideoService.queryById( videoId);
        return  JsonResult.success(qaVideo);
    }

    @PostMapping("/delete.json")
    @Function("qaVideo.qaVideo.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        qaVideoService.batchDelQaVideo(idList);
        return JsonResult.success();
    }


}
